package com.insigma.business.qrcode.soldier.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;


@Component
public class RedisLock {

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String LOCK_PREFIX = "redis_lock";

    public static final int LOCK_EXPIRE = 60000; 

    public boolean tryLock(String key){
        return tryLock(key, LOCK_EXPIRE);
    }

    
    public boolean tryLock(String key, int lockTime){
        String lock = LOCK_PREFIX + key;
        
        return (Boolean) redisTemplate.execute((RedisCallback) connection -> {

            long expireAt = System.currentTimeMillis() + lockTime + 1;
            Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes());
            connection.pExpire(lock.getBytes(), lockTime);
            if (acquire) {
                return true;
            } else {

                byte[] value = connection.get(lock.getBytes());

                if (Objects.nonNull(value) && value.length > 0) {

                    long expireTime = Long.parseLong(new String(value));

                    if (expireTime < System.currentTimeMillis()) {
                        
                        byte[] oldValue = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + lockTime + 1).getBytes());
                        
                        return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
                    }
                }
            }
            return false;
        });
    }

    
    public void unlock(String key) {
        redisTemplate.delete(key);
    }
}

